<template>
  <div>
    <n-grid x-gap="10">
      <n-grid-item :span="10">
        <n-card :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 255) + 'px'}" >
          <n-space justify="center">
            <n-el  v-if="props.programme.engineType=='MJ' && imageSrc != '' && imageSrc != null  "
                  style="background: var(--hover-color);margin-top:10px">
              <n-space style="padding: 10px;">
                <n-image
                  :width="400"
                  :src= imageSrc
                />
              </n-space>
            </n-el>

            <n-el v-if="props.programme.engineType=='SD' && imageSrc != '' && imageSrc != null  "
                  style="background: var(--hover-color);margin-top:10px">
              <n-space style="padding: 10px;">
                <n-image
                    :width="400"
                    :src= fileFunction.getViewFilePathByUserFileId(imageSrc)
                />
              </n-space>
            </n-el>
          </n-space>
        </n-card>
        <n-card style="margin-top: 5px;">
          <n-text v-if="progress !='' && progress != null">进度: {{progress}}</n-text>
          <n-form :label-width="100" ref="formRef">
            <n-form-item-gi path="prompt" label="正向提示词">
              <n-input v-model:value="prompt"  type="textarea" style="height: 80px"/>
              <n-button type="primary" style="height: 80px;width: 80px;margin-left:5px;"
                        @click="generateImage"
                        :loading="buttonLoading">
                生成
              </n-button>
            </n-form-item-gi>
          </n-form>
        </n-card>
      </n-grid-item>
      <n-grid-item :span="14">
        <n-form>
          <n-form-item :show-label="false" label="绘画资源选择" path="resourceId">
            <n-select
              :options="resourceOption"
              @update:value="resourceSelect">
            </n-select>
            <n-tooltip>
              <template #trigger>
                <n-button type="primary" @click="getResourceInfo"  style="margin-left:5px; ">刷新
                  <template #icon>
                    <n-icon>
                      <SyncCircleOutline/>
                    </n-icon>
                  </template>
                </n-button>
              </template>
              <span>刷新资源</span>
            </n-tooltip>
          </n-form-item>
        </n-form>
        <n-scrollbar trigger="none" :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 136) + 'px'}" >
          <SdImg2Img
              v-if="selectedResource.length > 0
              && props.programme.engineType=='SD'
              && props.programme.programmeType=='VIDEO'"
              ref="SdImg2ImgRef" :resourceId="selectedResource"
              :useProgrammeSetting="false">
          </SdImg2Img>
          <MjSetting
              ref="mjSettingRef"
              v-if="props.programme.engineType=='MJ'"
              :paintEngineConfig="props.programme.paintEngineConfig">
          </MjSetting>
          <Sdtext2ImgSetting
              model="programme"
              ref="sdTxt2ImgRef" :resourceId="selectedResource" v-if="selectedResource.length > 0 && props.programme.engineType=='SD' && props.programme.programmeType=='NOVEL' "  :paintEngineConfig="props.programme.paintEngineConfig"></Sdtext2ImgSetting>
          <FooocusSetting v-if="selectedResource.length > 0 && props.programme.engineType=='Fooocus'" resource-id="" :paintEngineConfig="props.programme.paintEngineConfig"></FooocusSetting>
         </n-scrollbar>
       </n-grid-item>
    </n-grid>
  </div>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, ref} from 'vue'
import {NButton} from "naive-ui";
//@ts-ignore
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {SyncCircleOutline} from "@vicons/ionicons5"
import SdImg2Img from '@/components/creator/boardConfig/sdImg2Img.vue'

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import {resourceController} from "@/api/resource/resourceController.api";
import MjSetting from "@/views/pages/create/components/mjSetting.vue";
import Sdtext2ImgSetting from "@/views/pages/create/components/sdtext2ImgSetting.vue";
import FooocusSetting from "@/views/pages/create/components/fooocusSetting.vue";
import {mjControllerApi} from "@/api/mj/mjController.api";
import {sdControllerApi} from "@/api/sd/sdController.api";

const mjSettingRef = ref(null)
const selectedPic = ref(null)
const picList = ref([])
const buttonLoading = ref(false)
const prompt = ref('')

const progress = ref()
const imageSrc = ref('')

const props = defineProps({
  programme: {
    type: Object,
    required: true
  }
})

const resourceOption = ref([])
const selectedResource = ref("")
const selectedResourceOption = ref({
  label: '',
  value: '',
  type: ''
})
const SdImg2ImgRef = ref(null)
const sdTxt2ImgRef = ref(null)
const getResourceInfo = async () => {
  try {
    const res = await resourceController.getSDResource(props.programme.engineType);
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id,
          type: item.type,
        });
      })
    } else {
      window.$message.error(res.msg);
    }
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

const resourceSelect = (value: string, option: any) => {
  selectedResource.value = value
  selectedResourceOption.value = option;

}


const validate = async () => {
  const isOk = ref(false)
  if (props.programme.engineType === 'MJ'){
    isOk.value = await mjSettingRef.value?.validate()
  }else if (props.programme.engineType === 'SD'){
    isOk.value = await sdTxt2ImgRef.value?.validate()
  }
  return isOk.value
}



/**提交任务**/
const mjGenerateImage =  async () => {
  buttonLoading.value = true
  const mjPrompt = {...props.programme.paintEngineConfig}
  mjPrompt.prompt = mjPrompt.prompt + "," +prompt.value
  mjControllerApi.generateText2ImgAndCheck(mjPrompt, 1000 * 60 * 5,progress,imageSrc).then(res=>{
    if(res.status === 'SUCCESS' ){
      progress.value = '100%'
      imageSrc.value = res.imageUrl
    }
    buttonLoading.value = false
  })
}


const sdGenerateImage =  async () => {
  buttonLoading.value = true
  console.log(props.programme.paintEngineConfig)
  const param = {
    sdResourceId: selectedResource.value,
    prompt: prompt.value + "," + props.programme.paintEngineConfig.defaultPrompt,
    negativePrompt: props.programme.paintEngineConfig.defaultNegativePrompt,
    steps : props.programme.paintEngineConfig.defaultSteps,
    resizeMode : props.programme.paintEngineConfig.defaultResizeMode,
    batchSize : props.programme.paintEngineConfig.defaultBatchSize,
    cfgScale : props.programme.paintEngineConfig.defaultCfgScale,
    seed : props.programme.paintEngineConfig.defaultSeed,
    width : props.programme.paintEngineConfig.defaultWidth,
    height : props.programme.paintEngineConfig.defaultHeight,
    samplerName : props.programme.paintEngineConfig.defaultSamplerName,
    restoreFaces : props.programme.paintEngineConfig.defaultRestoreFaces,
    enableHr : props.programme.paintEngineConfig.defaultEnableHr,
    hrUpscaler : props.programme.paintEngineConfig.defaultHrUpscaler,
    denoisingStrength : props.programme.paintEngineConfig.defaultDenoisingStrength,
    hrSecondPassSteps: props.programme.paintEngineConfig.defaultHrSecondPassSteps,
    hrScale: props.programme.paintEngineConfig.defaultHrScale
  }

  try {
    const data = await sdControllerApi.generateText2ImgAndCheck(param, 1000 * 120)
    console.log(data)
    const images = data.userFileId.split(',')
    imageSrc.value = images[0]
    buttonLoading.value = false
  }catch (e){
    buttonLoading.value = false

  }
}


onMounted(() => {
  getResourceInfo()
})



const generateImage = () =>{
  imageSrc.value = ''
  if (props.programme.engineType === 'MJ'){
    mjGenerateImage()
  }else if (props.programme.engineType === 'SD'){
    sdGenerateImage()
  }

}


defineExpose({
  validate
})

</script>
